import { SET_STORE_STATE, SET_LOCAL_STATE, SET_USER_LOCAL_LABEL } from './actionType';

import {useUserData} from '@/hooks/useUserData';




const { LOCAL_LABEL_PREFIX, SAVE_STATE_KEYS } = useUserData();




// 保存变量到本地存储中
const saveLifeData = function <T>(key: string, value: T): void {
	const userLocalLabel = uni.getStorageSync(LOCAL_LABEL_PREFIX);
	// localStorageValue = uni.getStorageSync(localStorageCurrentUserKey);
	// 判断变量名是否在需要存储的数组中
	if (SAVE_STATE_KEYS.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync(userLocalLabel);
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		uni.setStorageSync(userLocalLabel, tmp);
	}
}

export default {
	[SET_STORE_STATE]<T>(state: IStoreState, options: ISetStoreStateOptions<T>): void {
		// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
		let nameArr: string[] = options.name.split('.');
		let saveKey: string = '';
		let len: number = nameArr.length;
		if (len >= 2) {
			let obj = state[nameArr[0]];
			for (let i = 1; i < len - 1; i++) {
				obj = obj[nameArr[i]];
			}
			obj[nameArr[len - 1]] = options.value;
			saveKey = nameArr[0];
		} else {
			// 单层级变量，在state就是一个普通变量的情况
			state[options.name] = options.value;
			saveKey = options.name;
		}
	},
	[SET_LOCAL_STATE]<T>(state: IStoreState, options: ISetStoreStateOptions<T>): void {
		// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
		let nameArr: string[] = options.name.split('.');
		let saveKey: string = '';
		let len: number = nameArr.length;
		if (len >= 2) {
			let obj = state[nameArr[0]];
			for (let i = 1; i < len - 1; i++) {
				obj = obj[nameArr[i]];
			}
			obj[nameArr[len - 1]] = options.value;
			saveKey = nameArr[0];
		} else {
			// 单层级变量，在state就是一个普通变量的情况
			state[options.name] = options.value;
			saveKey = options.name;
		}
		saveLifeData(saveKey, state[saveKey])
	},
	[SET_USER_LOCAL_LABEL](state: IStoreState, payload: number): void {

	}
}